<template>
  <Card>
    <Cond @query="load" :model="pageIn" :disabled="!org.id">
      <CondItem title="关键字" field="q">
        <Input v-model="pageIn.q" placeholder="姓名/用户名" />
      </CondItem>
      <CondItem title="Email" field="cond.email">
        <Input v-model="pageIn.cond.email" />
      </CondItem>
      <CondItem title="手机" field="cond.mobile">
        <Input v-model="pageIn.cond.mobile" />
      </CondItem>
      <CondItem title="全部子级？" field="cond.isFindDescendant">
        <Switch v-model="pageIn.cond.isFindDescendant" />
      </CondItem>
      <CondItem title="昵称" field="cond.nickname">
        <Input v-model="pageIn.cond.nickname" />
      </CondItem>
      <CondItem title="性别" field="cond.gender" immediate>
        <ees-enum clazz="Gender" v-model="pageIn.cond.gender" />
      </CondItem>
      <template #op>
        <ButtonGroup>
          <Button type="primary" :disabled="!org.id" v-drawer="[UserSelect, `${org.name}/选择用户#2`, { condition: { orgId: org.id, isNot: true } }, onOk]"> 添加员工 </Button>
          <Button type="primary" :disabled="tableSelectDisabled" @click="onDelete">
            {{ tableSelectedMap.size ? `移除用户(${tableSelectedMap.size})` : '移除员工' }}
          </Button>
        </ButtonGroup>
      </template>
    </Cond>
    <Table
      :data="pageOut.records"
      :hoverable="false"
      :expandable="{ title: '角色', width: 80 }"
      @sorter-change="(f, m) => onSort(f, m, load)"
      :row-selection="tableRowSelect"
      @selection-change="onTableSelectChange"
      :loading="loading || saveLoading"
    >
      <template #columns>
        <TableColumn title="用户名" field="username" />
        <TableColumn title="姓名" field="name" />
        <TableColumn title="手机" field="mobile" />
        <TableColumn title="组织" :width="120" v-if="pageIn.cond.isFindDescendant">
          <template #cell="{ record }">
            <template v-if="record.orgs && record.orgs.length">
              <Tag v-for="item in record.orgs" :key="item.id">
                {{ item.name }}
              </Tag>
            </template>
          </template>
        </TableColumn>
        <TableColumn title="Email" field="email" />
        <TableColumn title="性别" field="gender" :sortable="$sortable">
          <template #cell="{ record }">
            <ees-format :value="record.gender" pattern="enum" params="Gender" />
          </template>
        </TableColumn>
      </template>
      <template #expand-row="{ record }">
        <ConfigProvider size="small">
          <Card>
            <role :parentData="record" />
          </Card>
        </ConfigProvider>
      </template>
    </Table>
    <ees-page v-model:pageIn="pageIn" :pageOut="pageOut" @change="load" />
  </Card>
</template>

<script setup>
import { Message, Switch, ConfigProvider, Card, Table, TableColumn, ButtonGroup, Button, Input, Cond, CondItem } from '@idmy/ui'
import { deleteOrgUserRef } from './services'
import { computed, ref, watch, watchEffect } from 'vue'
import { pageUser, createOrgUserRef } from './services'
import { useLoading, usePage, useDelete, useTableSelect } from '@idmy/core'
import Role from '../Role/index.vue'
import UserSelect from '@/components/user/select.vue'

const { tableRowSelect, tableServerMap, tableSelectDisabled, onTableSelectClear, onTableSelectChange, tableSelectedMap } = useTableSelect()

const props = defineProps({
  parentData: {
    type: Object,
    required: true,
    default: () => {
      return {
        id: null,
      }
    },
  },
})

const { pageIn, pageOut, onSort } = usePage({
  sorts: ['createdAt', 'desc'],
  condition: {
    isFindDescendant: false,
  },
})

const org = computed(() => props.parentData)
const [load, loading] = useLoading(async () => {
  if (!!org.value.id) {
    pageIn.cond.orgId = org.value.id
    pageOut.value = await pageUser(pageIn)
    pageOut.value.records.forEach(item => tableServerMap.set(item.id, item))
  } else {
    pageOut.value = { total: 0, records: [] }
    onTableSelectClear()
  }
})

watch(
  org,
  () => {
    load()
    onTableSelectClear()
  },
  { immediate: true }
)

const [onOk, saveLoading] = useLoading(async ({ ids }) => {
  const orgId = org.value.id
  const arr = ids.map(userId => ({ orgId, userId }))
  await createOrgUserRef(arr)
  Message.success('保存成功')
  load()
})

const onDelete = useDelete(async () => {
  await deleteOrgUserRef(org.value.id, tableRowSelect.selectedRowKeys)
  onTableSelectClear()
}, load)
</script>
